import os
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal
from omegaconf import OmegaConf
from DrissionPage import ChromiumOptions

# Import from utils (assuming these functions will be in utils)
from modules.utils.register_utils import register_cursor

class RegisterWorker(QThread):
    # Define signals
    update_signal = pyqtSignal(str)  # Update log
    result_signal = pyqtSignal(list)  # Return results
    finished_signal = pyqtSignal()  # Registration completion signal

    def __init__(self, number, max_workers, enable_headless, enable_browser_log, hide_account_info, auto_close_browser=True, chrome_settings=None):
        super().__init__()
        self.number = number
        self.max_workers = max_workers
        self.enable_headless = enable_headless
        self.enable_browser_log = enable_browser_log
        self.hide_account_info = hide_account_info
        self.auto_close_browser = auto_close_browser
        self.chrome_settings = chrome_settings or {}
        
        # Add stop flag
        self.stop_requested = False
        
        # 日志回调
        self.log_callback = None
    
    def set_log_callback(self, callback):
        """设置日志回调函数"""
        self.log_callback = callback
        
    def run(self):
        try:
            # Create configuration object
            config = OmegaConf.create({
                "number": self.number,
                "max_workers": self.max_workers,
                "delete_low_balance_account": True,
                "delete_low_balance_account_threshold": 50,
                "email_server": {
                    "name": "outlook_web"
                },
                "enable_headless": self.enable_headless,
                "enable_browser_log": self.enable_browser_log,
                "hide_account_info": self.hide_account_info,
                "auto_close_browser": self.auto_close_browser
            })
            
            # Set environment variables
            os.environ['ENABLE_HEADLESS'] = 'true' if self.enable_headless else 'false'
            os.environ['ENABLE_BROWSER_LOG'] = 'true' if self.enable_browser_log else 'false'
            os.environ['HIDE_ACCOUNT_INFO'] = 'true' if self.hide_account_info else 'false'
            
            # Configure Chrome options
            chrome_options = None
            if self.chrome_settings:
                chrome_options = self.setup_chrome_options()
            
            # Execute registration process
            self.update_signal.emit("开始注册过程...")
            
            # Safe execution with stop check
            results = []
            try:
                # Check for stop before starting
                if self.stop_requested:
                    self.update_signal.emit("注册已取消")
                    return
                
                results = register_cursor(
                    config, 
                    chrome_options=chrome_options,
                    stop_check_callback=self.check_stop_requested,
                    log_callback=self.log_message
                )
                
            except Exception as e:
                if self.stop_requested:
                    self.update_signal.emit("注册已停止")
                else:
                    self.update_signal.emit(f"注册过程异常: {str(e)}")
            
            # Only send results if we weren't stopped
            if not self.stop_requested and results:
                # Send result signal
                self.result_signal.emit(results)
                self.update_signal.emit(f"注册完成，成功注册 {len(results)} 个账号")
            
        except Exception as e:
            if not self.stop_requested:
                self.update_signal.emit(f"注册过程出错: {str(e)}")
        
        finally:
            self.finished_signal.emit()
    
    def log_message(self, message):
        """日志消息处理"""
        # 使用信号发送日志到UI线程
        self.update_signal.emit(message)
        # 如果有自定义日志回调，也调用它
        if self.log_callback:
            self.log_callback(message)
    
    def check_stop_requested(self):
        """用于在注册过程中检查是否请求停止"""
        # Add a small sleep to reduce CPU usage when checking frequently
        time.sleep(0.1)
        return self.stop_requested
            
    def setup_chrome_options(self):
        """设置Chrome浏览器选项"""
        try:
            options = ChromiumOptions()
            
            # Set Chrome executable path if provided
            chrome_path = self.chrome_settings.get('chrome_path')
            if chrome_path and os.path.exists(chrome_path):
                options.set_browser_path(chrome_path)
                
            # Set user data directory if provided
            user_data_dir = self.chrome_settings.get('user_data_dir')
            if user_data_dir and os.path.exists(user_data_dir):
                options.set_user_data_path(user_data_dir)
            
            # Set additional Chrome options
            if self.chrome_settings.get('disable_gpu', False):
                options.add_argument('--disable-gpu')
                
            if self.chrome_settings.get('disable_extensions', False):
                options.add_argument('--disable-extensions')
                
            if self.chrome_settings.get('incognito', False):
                options.add_argument('--incognito')
                
            # Set headless mode if enabled
            if self.enable_headless:
                options.headless(True)
                
            return options
            
        except Exception as e:
            self.update_signal.emit(f"Chrome选项设置错误: {str(e)}")
            return None 